#!/usr/bin/env python
# -*- coding:utf-8 -*-
# © 2013 Ethan Tân

__author__ = "Ethan Tân"

import cgi
import webapp2
import jinja2
import os, urllib2

from django.conf.urls import patterns

from google.appengine.ext import db
# from google.appengine.ext import ndb
from google.appengine.api import memcache, users

from parse import parse, generate_tebok_ID
from handleDB import Tebok, Khokng
# import data

jinja_environment = jinja2.Environment(
  loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))

_TEBOK_INDEX_NAME="teboks"

openid_providers = {
    'Google'   : 'https://www.google.com/accounts/o8/id',
    'Yahoo'    : 'yahoo.com',
    'MySpace'  : 'myspace.com',
    'AOL'      : 'aol.com',
    'MyOpenID' : 'myopenid.com'
    # add more here
}

class MainPage(webapp2.RequestHandler):
  def get(self):
    urlpatterns = patterns('',
      (r'^articles/2003/$', 'news.views.special_case_2003'),
      (r'^articles/(\d{4})/$', 'news.views.year_archive'),
      (r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'),
      (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'),
    )
    user = users.get_current_user()
    if user:  # signed in already
      self.response.out.write('Hello <em>%s</em>! [<a href="%s">sign out</a>]' % (
        user.nickname(), users.create_logout_url(self.request.uri)))
    else:     # let user choose authenticator
      self.response.out.write('Hello world! Sign in at: ')
      for name, uri in openid_providers.items():
        self.response.out.write('[<a href="%s">%s</a>]' % (
          users.create_login_url(federated_identity=uri), name))

    template_values = {}

    template = jinja_environment.get_template('index.html')
    self.response.out.write(template.render(template_values))

class EditPage(webapp2.RequestHandler):
  def get(self):
    dev = cgi.escape(self.request.get('dev'))
    template_values = { "edit": True, "dev": dev }

    template = jinja_environment.get_template('index.html')
    self.response.out.write(template.render(template_values))


class UploadExamPage(webapp2.RequestHandler):
  def get(self):
    template_values = { "uploadexam": True }

    template = jinja_environment.get_template('index.html')
    self.response.out.write(template.render(template_values))

class SangTebokPage(webapp2.RequestHandler):
  def post(self):
    o_thauhang = self.request.get('thauhang') #content
    o_nihun = self.request.get('nihun') #year
    o_hothau = self.request.get('hothau') #index
    o_toeho = self.request.get('toeho') #index
    o_key_name = generate_tebok_ID(o_nihun, o_hothau, o_toeho, o_thauhang)
    tebok = Tebok(key_name = o_key_name,
                  nihun = o_nihun,
                  hothau = o_hothau,
                  toeho = o_toeho,
                  thauhang = o_thauhang
                  )
    
    tebok.choopiat = self.request.get('choopiat') #category
    tebok.khochhi = self.request.get('khochhi') #exam
    tebok.khobok = self.request.get('khobok') #subject
    tebok.tootoo = str(self.request.get('tootoo')) #figure
    tebok.put()

    # ques = search.Document(
    #   doc_id = "temp-doc-id",
    #   fields = [search.TextField(name="nihun", value="self.request.get('nihun')"),
    #           search.TextField(name="thauhang", value="self.request.get('thauhang')")])

    # try:
    #   search.Index(name=_TEBOK_INDEX_NAME).put(ques)
    # except search.Error:
    #   logging.exception('Put failed')

    template_values = { "sangTebok": True, "xxxx": False}
    #self.response.out.write('處理中...')
    template = jinja_environment.get_template('index.html')
    self.response.out.write(template.render(template_values))
#    xml = urllib2.unquote(self.request.get('xml2').encode('utf-8'))
#    files = self.request.POST.getall('files[]')
#    qId = store2Database(xml, files)
    # redirect to show page
    self.redirect('/moex/%s' % tebok.key().name())


class TiankuiTebokPage(webapp2.RequestHandler):
  def get(self, tebok_key_name):
    ss_teboks = db.GqlQuery("SELECT * FROM Tebok WHERE key_name = :1", tebok_key_name)
    if not ss_teboks:
      # tebok_key = ndb.Key('Tebok', tebok_key_name)
      # s_tebok = Tebok.get(tebok_key)
      self.redirect("/")
      return
    else:
      tebok_tauhang_string = ""
      for s_tebok in ss_teboks:
        tebok_tauhang_string += s_tebok.thauhang

    # tebok_k = db.Key.from_path('Tebok', tebok_key_name)
    # s_tebok = db.get(tebok_k)

    # s_tebok = Tebok.get_by_key_name(tebok_key_name)
    # tebok_tauhang_string = ""
    # tebok_tauhang_string += s_tebok.thauhang    
    template_values = { "show": True, "test": tebok_tauhang_string }
#    self.generate()

    template = jinja_environment.get_template('index.html')
    self.response.out.write(template.render(template_values))

  def post(self):
    # for preview of xml to be uploaded
    xml = urllib2.unquote(self.request.get('xml')).encode('utf-8')
    self.response.out.write(parse(xml))


class ImageServe(webapp2.RequestHandler):
  def get(self):
    imageId = urllib2.unquote(self.request.get('id'))
    data = getImageData(imageId)
    if (data == None):
      # http 404 not found
      self.error(404)
    else:
      self.response.out.write(data)


class ListPage(webapp2.RequestHandler):
  def get(self):
    listHTMLStr = getAllXMLList()

    template_values = { "list": True, "listHTMLStr": listHTMLStr }

    template = jinja_environment.get_template('index.html')
    self.response.out.write(template.render(template_values))
    teboks = db.GqlQuery("SELECT * "
                            "FROM Tebok "
                            "WHERE ANCESTOR IS :1 "
                            "ORDER BY nihun DESC LIMIT 10")

class ChhoeTebok(webapp2.RequestHandler):
  def get(self):
    # Query the index.
    o_teboks = db.Key.from_path('Tebok', 'asalieri', 'Address', 1)

    try:
      results = index.search(query=search.Query('thauhang:a',
                              options=search.QueryOptions(limit=20,
                              cursor=search.Cursor(per_result=True))))
      # Iterate through the search results.
      xxx = None
      cursor = None
      for scored_document in results:
        # process the scored_document
        cursor = scored_document.cursor
        xxx += scored_document.fields.thauhang
    except search.Error:
      logging.exception('Search failed')

    template_values = { "chhoeTebok": True, "chhoetioh": xxx}
    template = jinja_environment.get_template('index.html')
    self.response.out.write(template.render(template_values))

app = webapp2.WSGIApplication([('/', MainPage),
                               ('/edit', EditPage),
                               ('/list', ListPage),
                               ('/image', ImageServe),
                               ('/uploadexam', UploadExamPage),
                               ('/sangTebok', SangTebokPage),
                               ('/moex/([-\w]+)', TiankuiTebokPage),
                               ('/chhoeTebok', ChhoeTebok)],
                              debug=True)
